<template>
  <div class="user-orders">
    <!-- 搜索区域 -->
    <el-card class="search-area">
      <el-form :inline="true" :model="queryParams" @submit.prevent="handleSearch">
        <el-form-item label="订单编号">
          <el-input
            v-model="queryParams.orderNo"
            placeholder="请输入订单编号"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
            <el-option label="待付款" value="0" />
            <el-option label="待发货" value="1" />
            <el-option label="待收货" value="2" />
            <el-option label="已完成" value="3" />
            <el-option label="已取消" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card v-loading="loading" class="order-list">
      <template v-if="orderList.length">
        <div v-for="order in orderList" :key="order.orderId" class="order-item">
          <el-card shadow="hover">
            <div class="order-header">
              <div class="order-info">
                <span class="order-no">订单编号：{{ order.orderNo }}</span>
                <span class="order-time">下单时间：{{ parseTime(order.createTime) }}</span>
              </div>
              <el-tag :type="getStatusType(order.status)">{{ getStatusText(order.status) }}</el-tag>
            </div>
            <div class="order-content">
              <div class="product-item">
                <el-image 
                  :src="baseUrl + order.productImage" 
                  :preview-src-list="[baseUrl + order.productImage]" 
                  class="product-image" 
                />
                <div class="product-info">
                  <h4>{{ order.productName }}</h4>
                  <p class="price">¥{{ order.price }}</p>
                  <p class="quantity">x{{ order.quantity }}</p>
                </div>
              </div>
            </div>
            <div class="order-footer">
              <div class="total">
                <span>共{{ order.quantity }}件商品</span>
                <span class="amount">总计：¥{{ order.totalAmount }}</span>
              </div>
              <div class="actions">
                <el-button
                  v-if="order.status === '0'"
                  type="primary"
                  @click="handlePay(order)"
                >立即付款</el-button>
                <el-button
                  v-if="order.status === '2'"
                  type="success"
                  @click="handleConfirm(order)"
                >确认收货</el-button>
                <el-button
                  v-if="order.status === '0'"
                  type="danger"
                  @click="handleCancel(order)"
                >取消订单</el-button>
                <el-button @click="viewDetail(order)">查看详情</el-button>
              </div>
            </div>
          </el-card>
        </div>
      </template>
      <el-empty v-else description="暂无订单" />
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 支付确认对话框 -->
    <el-dialog
      title="确认支付"
      v-model="payDialogVisible"
      width="30%"
    >
      <div class="pay-dialog-content">
        <p>订单金额：<span class="amount">¥{{ currentOrder.totalAmount }}</span></p>
        <p class="tip">这是一个模拟支付流程，点击确认后将直接完成支付</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPay" :loading="payLoading">
            确认支付
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { listOrder, cancelOrder, confirmOrder, payOrder } from '@/api/user/order'
import { parseTime } from '@/utils/ruoyi'

const router = useRouter()
const loading = ref(false)
const total = ref(0)
const orderList = ref([])
const payDialogVisible = ref(false)
const payLoading = ref(false)
const currentOrder = ref({})
const baseUrl = import.meta.env.VITE_APP_BASE_API

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  orderNo: undefined,
  status: undefined
})

// 获取订单列表
const getList = async () => {
  loading.value = true
  try {
    const res = await listOrder(queryParams.value)
    orderList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  } finally {
    loading.value = false
  }
}

// 获取订单状态类型
const getStatusType = (status) => {
  const statusMap = {
    '0': 'warning',
    '1': 'primary',
    '2': 'success',
    '3': 'info',
    '4': 'danger'
  }
  return statusMap[status]
}

// 获取订单状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待付款',
    '1': '待发货',
    '2': '待收货',
    '3': '已完成',
    '4': '已取消'
  }
  return statusMap[status]
}

// 搜索按钮操作
const handleSearch = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    orderNo: undefined,
    status: undefined
  }
  getList()
}

// 立即付款
const handlePay = (order) => {
  currentOrder.value = order
  payDialogVisible.value = true
}

// 确认收货
const handleConfirm = (order) => {
  ElMessageBox.confirm('确认要收货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await confirmOrder(order.orderId)
      if (res.code === 200) {
        ElMessage.success('确认收货成功')
        getList()
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败')
    }
  })
}

// 取消订单
const handleCancel = (order) => {
  ElMessageBox.confirm('确认要取消订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await cancelOrder(order.orderId)
      if (res.code === 200) {
        ElMessage.success('取消订单成功')
        getList()
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  })
}

// 查看订单详情
const viewDetail = (order) => {
  router.push(`/user/orders/detail/${order.orderId}`)
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 确认支付
const confirmPay = async () => {
  payLoading.value = true
  try {
    const res = await payOrder(currentOrder.value.orderId)
    if (res.code === 200) {
      ElMessage.success('支付成功')
      payDialogVisible.value = false
      getList() // 刷新订单列表
    }
  } catch (error) {
    console.error('支付失败:', error)
    ElMessage.error('支付失败')
  } finally {
    payLoading.value = false
  }
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.user-orders {
  padding: 20px;

  .search-area {
    margin-bottom: 20px;
  }

  .order-list {
    .order-item {
      margin-bottom: 20px;

      &:last-child {
        margin-bottom: 0;
      }

      .order-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .order-info {
          .order-no {
            margin-right: 20px;
            color: #666;
          }

          .order-time {
            color: #666;
          }
        }
      }

      .order-content {
        .product-item {
          display: flex;
          align-items: center;
          padding: 10px 0;
          border-bottom: 1px solid #eee;

          .product-image {
            width: 80px;
            height: 80px;
            object-fit: cover;
            margin-right: 15px;
          }

          .product-info {
            flex: 1;

            h4 {
              margin: 0 0 10px;
              font-size: 14px;
            }

            .price {
              color: #f56c6c;
              margin: 5px 0;
            }

            .quantity {
              color: #666;
            }
          }
        }
      }

      .order-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 15px;

        .total {
          .amount {
            margin-left: 20px;
            color: #f56c6c;
            font-weight: bold;
          }
        }

        .actions {
          .el-button {
            margin-left: 10px;
          }
        }
      }
    }
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }
}

.pay-dialog-content {
  text-align: center;
  
  .amount {
    color: #f56c6c;
    font-size: 24px;
    font-weight: bold;
  }

  .tip {
    color: #909399;
    margin-top: 10px;
    font-size: 14px;
  }
}
</style> 